<?php
/**
 * 单一窗口 * 回执文件下载
 */
namespace ordersync;

use ordersync\component\Customs;
use request\Request;
use SimpleXMLElement;

class CustomsDownloadOneFileRequest extends Request {

    protected $method = 'soap';
    protected $apiMethodName = 'downloadOneFile';
    protected $otherResultNames = ['downloadFileInfo'];
    protected $downloadFileInfo = null;
    use Customs;

    public function __construct()
    {
        $url = 'https://edi1500.sditds.com:7702/service_1501_webservice/ws/edi/EnteTransportRecvFiles?wsdl';
        $this->setUrl($url);

        $context = stream_context_create( array (
            'ssl' => array (
                'verify_peer' => false,
                'allow_self_signed' => true
            ),
        ));
        $options['stream_context'] = $context;
        $this->setRequestOptions($options);
    }

    /**
     * @return array SimpleXMLElement
     */
    public function getDownloadFileInfo()
    {
        return $this->downloadFileInfo;
    }

    /**
     * @param $downloadFileInfo
     */
    public function setDownloadFileInfo($downloadFileInfo)
    {
        $downloadFileInfo = json_decode(json_encode($downloadFileInfo), true);
        $fileInfo = base64_decode($downloadFileInfo['fileBase64']);

        $zipPath = TEMP_DOWNLOAD_PATH . '/'.date('YmdHis').mt_rand(100000, 999999).'.zip';
        file_rput_contents($zipPath, $fileInfo);

        $extPath = preg_replace('/\.zip$/', '', $zipPath);
        $zip = new \ZipArchive();
        $zip->open($zipPath);   //打开压缩包
        $zip->extractTo($extPath);   //向压缩包中添加文件
        $zip->close();  //关闭压缩包

        unlink($zipPath);   // 删除缓存zip

        $data = scandir($extPath);

        if(!empty($data)){
            foreach ($data as $value){
                if($value != '.' && $value != '..'){
                    $subPath = $extPath."/".$value;
                    //加载解析xml
                    $this->downloadFileInfo[] = simplexml_load_string(file_get_contents($subPath));     // 一个压缩包里可能有多个xml

                    // unlink($subPath);     暂时不删除下载文件，测试下载内容
                }
            }
            // rmdir($extPath);   // 删除临时文件  （暂时不删除下载文件，测试下载内容）
        }
    }

    /**
     * 请求数据转化
     * @param array $params
     * @param int $dimension // 数组维度
     * @return array
     */
    protected function requestTransfer($params = [], $dimension = 1)
    {
        return [
            'enteLoginInfo' => [
                'loginName' => config('customs_config.loginName'),
                'loginPassword' => $this->strEncrypt(config('customs_config.loginPassword')),
            ],
            'fileTempID' => $params['file_temp_id'],
            'expandAttribute' => null
        ];
    }
}